package edzis.translatebuddy.view
{
	import com.yahoo.astra.fl.controls.TabBar;
	import edzis.translatebuddy.events.DataProxyEvent;
	import edzis.translatebuddy.model.AppProxy;
	import edzis.translatebuddy.model.DataProxy;
	import flash.events.Event;
	import org.puremvc.as3.multicore.interfaces.IMediator;
	import org.puremvc.as3.multicore.interfaces.INotification;
	import org.puremvc.as3.multicore.patterns.mediator.Mediator;
	
	import edzis.translatebuddy.ApplicationFacade;
	
	import edzis.translatebuddy.view.components.ChoseSession;

	public class NavigationMediator extends Mediator implements IMediator
	{
		
		public static const NAME:String = 'NavigationMediator';
		
		private var view			: TabBar;
		private var _dataProxy		: DataProxy;
		private var _appProxy		: AppProxy;
		
		
		public function NavigationMediator(viewComponent:Object = null) {
			super(NAME, viewComponent);
			view = viewComponent as TabBar;
			view.autoSizeTabsToTextWidth = false;
			view.addEventListener(Event.CHANGE, onSelectionChange);
			// Add Listeners
			if (view.stage) onAddEdToStage(null);
			else view.addEventListener(Event.ADDED_TO_STAGE, onAddEdToStage);
		}
		
		override public function onRegister():void {
			super.onRegister();
			_appProxy = facade.retrieveProxy(AppProxy.NAME) as AppProxy;
		}
		
		
	/************************************
	/*	PRIVATE LISTENERS
	/***********************************/
		
		private function onSelectionChange(e:Event):void {
		//	sendNotification(AppProxy.APP_STATE_CHANGE, view.selectedItem.data);
			_appProxy.appState = view.selectedItem.data;
		}
		
		private function onAddEdToStage(e:Event):void {
			view.removeEventListener(Event.ADDED_TO_STAGE, onAddEdToStage);
			view.stage.addEventListener(Event.RESIZE, onResize);
			onResize(null);
		}
		
		private function onResize(e:Event):void {
			view.width = view.stage.stageWidth;
		}
		
		
		
		override public function listNotificationInterests():Array {
			return [
				AppProxy.APP_STATE_CHANGE
			 ];
		}
		
		override public function handleNotification(notification:INotification):void {
			
			switch ( notification.getName() ) {
				case AppProxy.APP_STATE_CHANGE:
					var newState:String = notification.getBody() as String;
					for (var i:int = 0; i < view.dataProvider.length; i++) {
						if (view.dataProvider.getItemAt(i).data == newState) {
							if(view.selectedIndex != i) view.selectedIndex = i;
						}
					}
					break;
					
				default : break;
			}
				
		}
		
	}
}